/**
 * 地图相关
 */
var map;
$(document).ready(function () {
    map = new AMap.Map('saul_map', {
        resizeEnable: true,
        zoom: 8,
        viewMode: '3D',
        mapStyle: 'amap://styles/b38944ba08acddbe213ee39dcdb38203',  // 地图样式
    });
});

var markers = [];
// 列表数据
var provinces = [];
for (let i = 0; i < 20; i++) {
    let minX = (
        Math.floor(Math.random()*(118 - 100) + 100)
    ) + .994142;
    let minY = (
        Math.floor(Math.random()*(40 - 25) + 25)
    ) + .355468;
    provinces.push({
        id: i,
        name: '设备' + i,
        center: [minX,minY],
        type: (
            Math.floor((Math.random() * 100)) < 50 ? 0 : 1
        ),
        // type: 1,
        number: Math.floor((Math.random() * 10000) * i),
        Template: '设备' + i,
        dizhi: '我在德玛西亚' + i + '区',
        policeZS: ''+Math.floor((Math.random() * 1000) + 1000)+'',
        policeOK: ''+Math.floor((Math.random() * 1000) + 1000)+'',
        policeNO: ''+Math.floor((Math.random() * 1000) + 1000)+''
    })
}
$(document).ready(function () {
    var infoWindow = new AMap.InfoWindow({offset: new AMap.Pixel(0, 0), anchor: 'top-left'});
    AMapUI.loadUI(
        ['misc/MarkerList', 'overlay/SvgMarker', 'overlay/SimpleInfoWindow'],
        function (MarkerList, SvgMarker, SimpleInfoWindow) {

            if (!SvgMarker.supportSvg) {
                alert('当前环境不支持SVG')
            }

            var markerList = new MarkerList({
                map: map,
                listContainer: 'my-list',
                listElementEvents: ['click', 'mouseenter', 'mouseleave'],
                markerEvents: ['click', 'mouseover', 'mouseout'],
                infoWindowEvents: ['click', 'mouseover', 'mouseout'],
                getDataId: function (dataItem, id) {
                    return dataItem.id
                },
                getPosition: function (dataItem) {
                    return dataItem.center
                },
                getMarker: function (dataItem, context, recycledMarker) {
                    var label = dataItem.name;
                    if (recycledMarker) {
                        recycledMarker.setIconLabel(label);
                        return recycledMarker
                    }
                },
                getListElement: function (dataItem, context, recycledListElement) {
                    if (dataItem.type === 1) {
                        tpl = '<p><span style="background: #00F2F9"></span>设备类型: <%-dataItem.name%> <br><span></span>安装位置: <%-dataItem.dizhi%></p>'
                    } else {
                        tpl = '<p><span style="background: #DD4F42"></span>设备类型: <%-dataItem.name%> <br><span></span>安装位置:  <%-dataItem.dizhi%></p>'
                    }
                    var content = MarkerList.utils.template(tpl, {dataItem: dataItem, dataIndex: context.index});
                    if (recycledListElement) {
                        recycledListElement.innerHTML = content;
                        return recycledListElement
                    }
                    return content
                },
                getInfoWindow: function (dataItem, context, recycledInfoWindow, content2) {
                    let policeZS = dataItem.policeZS;
                    let policeNO = dataItem.policeNO;
                    let policeOK = dataItem.policeOK;
                    context =
                        `
                        <div class="map-details">
                            <div class="maker-top">
                                <img src="images/de_ma2.png" class="" alt="">
                                <span>${ dataItem.name }</span>
                                <img src="images/close.png" class="amap-ui-infowindow-close clearImg" alt="x">
                            </div>
                            <div class="maker-Num">
                                <div class="warn">
                                    <p>报警总数</p>
                                    <div class="warn-span" >
                                        <span>${ policeZS.charAt(0) }</span>
                                        <span>${ policeZS.charAt(1) }</span>
                                        <span>${ policeZS.charAt(2) }</span>
                                        <span>${ policeZS.charAt(3) }</span>
                                    </div>
                                </div>
                                <div class="warn">
                                    <p>未处理报警</p>
                                    <div class="warn-span">
                                        <span>${ policeNO.charAt(0) }</span>
                                        <span>${ policeNO.charAt(1) }</span>
                                        <span>${ policeNO.charAt(2) }</span>
                                        <span>${ policeNO.charAt(3) }</span>
                                    </div>
                                </div>
                                <div class="warn">
                                    <p>已处理报警</p>
                                    <div class="warn-span">
                                        <span>${ policeOK.charAt(0) }</span>
                                        <span>${ policeOK.charAt(1) }</span>
                                        <span>${ policeOK.charAt(2) }</span>
                                        <span>${ policeOK.charAt(3) }</span>
                                    </div>
                                </div>
                            </div>
                            <div class="maker-other">
                                <p>
                                    <span>设备编号</span>
                                    <span>${ dataItem.number }</span>
                                </p>
                                <p>
                                    <span>从机地址</span>
                                    <span>${ dataItem.Template }</span>
                                </p>
                                <p>
                                    <span>设备地址</span>
                                    <span id="">${ dataItem.dizhi }</span>
                                </p>
                            </div>
                        </div>
                        `
                    return new SimpleInfoWindow({offset: new AMap.Pixel(-12, -12), anchor: 'bottom-center', infoBody: context})
                }
            });

            for (let i = 0; i < provinces.length; i++) {
                let marker = null;
                if (provinces[i].type === 0) {
                    let icon = new AMap.Icon({
                        image: 'images/leave.png',
                        fitZoom: 14,
                        scaleFactor: 2,
                        maxScale: 2,
                        minScale: 1
                    });
                    marker = new AMap.Marker({
                        icon: icon,
                        position: provinces[i].center,
                        offset: new AMap.Pixel(-12, -12),
                        zIndex: 101,
                        title: provinces[i].name,
                        extData: {id: provinces[i].name},
                        map: map
                    })
                }
                else {
                        marker = new AMap.Marker({
                        position: provinces[i].center,
                        title: provinces[i].name,
                        map: map
                    })
                }

                let name = provinces[i].name;
                marker.content = '<p class="taiwan">' + name + '</p>';
                marker.on('mouseover', markerClick);
                marker.emit('mouseover', {target: marker});
                // 地图圆点
                // marker.on('click', markerClickov);
                markers.push(marker);
            }
            markerList.on('selectedChanged', function (event, info) {
                $(".deviceList .container p").click(function (eve) {
                    $(this).addClass("map_active_p").siblings().removeClass("map_active_p")
                })
            });
            markerList.render(provinces);
            // 创建 infoWindow 实例
            function markerClick(e) {
                infoWindow.setContent(e.target.content);
                infoWindow.open(map, e.target.getPosition());
            }
            map.setFitView();
        });

});


// 总数, 在线, 离线
var Total = 0, statusks = 0, Endks = 0;
provinces.forEach(function (item){
    item.type === 1 ? statusks++ : Endks++
    Total = statusks + Endks;
})

/**
 * 计算 10 转换 1000
 * @param digit
 * @param num
 * @returns {string}
 */
function setStr(digit, num){
    let strNum = String(digit)
    return strNum.substring(0, strNum.length - String(num).length) + num
}

let arr = $("#deviceNum span")
for (let i = 0; i< arr.length; i++){
    arr[i].innerHTML = setStr("0000", Total)[i]
    $("#statusks span")[i].innerHTML = setStr("0000", statusks)[i]
    $("#Endks span")[i].innerHTML = setStr("0000", Endks)[i]
}



var dom1 = document.getElementById("runRate");
var myChart1 = echarts.init(dom1);
var app1 = {};
option = null;
app1.title = '环形图';
var centervalue = statusks / (statusks + Endks) * 100;
option = {
    tooltip: {trigger: 'item', formatter: "{a} <br/>{b}: {c}"},
    color: ['#01B0F1', 'rgba(255,255,255,0.1)'],
    series: [
      {
        name: '设备概括',
        type: 'pie',
        radius: ['70%', '88%'],
        avoidLabelOverlap: false,
        label: {
          show: true,
          position: 'center',
          formatter: function (argument) {
            return '在线率\r\n\r\n' + centervalue.toFixed(2) + '%';
          },
          textStyle: {
            fontSize: 15,
            color: '#39CCCC'
          }
        },
        labelLine: {normal: {show: false}},
        data: [
          {value: statusks, name: '在线'},
          {value: Endks, name: '离线'}
        ]
      },
      {
        type: 'pie',
        silent: true,
        radius: ['99%', '99.5%'],
        label: {show: false},
        data: [{value: 100}]
      }
    ]
};
if (option && typeof option === "object") {
    myChart1.setOption(option, true);
    window.addEventListener("resize", function () {
        myChart1.resize()
    })
}


/**
 * 右侧报警相关
 * @type {*[]}
 */

var newbaojing = [];
for (let i = 0; i < 50; i++) {
    // 1 异常 0正常
    newbaojing.push({
      status: (
          Math.floor((Math.random() * 100)) < 50 ? 0 : 1
      ),
      alarmId: Math.floor((Math.random() * 10000) * i),
      shebei: '设备' + i,
      center: '我是第' + i + '条报警内容',
      Position: '我的安装位置在德玛西亚' + i + '区',
    })
}
for (let s = 0; s < newbaojing.length; s++) {
    let shebei = newbaojing[s].shebei;
    let center = newbaojing[s].center;
    let Position = newbaojing[s].Position;
    let status = newbaojing[s].status;
    let alarmId = newbaojing[s].alarmId;
    let add = ''
    if (status === 1)  add = 'stateStyle'
    let html =
        `
            <div class="ac-list">   
              <div class="hover ${ add }">
                <h6>设备：<span>${ shebei }</span></h6>  
                <h6>内容：<span>${ center }</span></h6>  
                <h6>安装位置：<span>${ Position }</span></h6>  
                <p>${ status }</p> 
                <p>${ alarmId }</p> 
               </div>
               <img src="images/bjxx_border.png" alt="">
            </div>
           `
    $("#alarmContent").append(html)
}
$("#alarmContent .hover").click(function (even) {
    // $(this).addClass("div_active").siblings().removeClass("div_active");
    let shebei = $(this).children('.ac-list h6:nth-child(1)').html();
    let center = $(this).children('.ac-list h6:nth-child(2)').html();
    let Position = $(this).children('.ac-list h6:nth-child(3)').html();
    let status = $(this).children('.ac-list p:nth-child(4)').html();
    let alarmId = $(this).children('.ac-list p:nth-child(5)').html();
    let state,state1
    if (status === '0'){
        state = 'display: none'
    }else {
        state1 = 'display: none'
    }
    let errMsg =
        `
          <div class="errMsg-div">
            <div id="loading">
                <div id="loading_i"><i class="layui-icon layui-icon-loading"></i></div>
            </div>
            <img class="close" id="close" src="images/close.png" alt="">
            <div class="details">
              <p>${ shebei }</p>
              <p>${ center }</p>
              <p>${ Position }</p>
            </div>
            <div class="alarm">
               <img src="images/de_ma2.png" alt="">
               <span>报警处理</span>
            </div>
            <div class="alarm" style="${ state1 }">
               <span>处理结果：已处理</span>
            </div>
            <div class="alarm-form" style="${ state }">
               <form id="fromUpdate" action="">
                 <p>报警处理：    
                    <label class="alarmRadio" id="rdWell" for="male">
                      <span><b></b></span>
                      <input type="radio" id="male" name="sex" value="male">确认
                    </label>
                    <label class="alarmRadio" id="cancel" for="female">
                      <span><b></b></span>
                      <input type="radio" id="female" name="sex" value="female">误报
                    </label>
                 </p>
                 <p>处理描述：</p>
                 <div class="MText">
                    <input name="id" type="hidden" value="' + alarmId + '">             
                    <textarea maxlength="60" rows="3" name="text" placeholder="处理描述"  class="el-textarea__inner" style="resize: none; min-height: 35px;"></textarea>
                 </div>
                 <p class="submit"><input id="update" type="button" value="提交"></p>
               </form>
            </div>
          </div>
        `
    $('#popupNew').empty().append(errMsg);
    $("#popupNew").fadeIn();


    $("#close").click(function () {
        $("#popupNew").slideUp();
    });

    /**
     * 弹窗单选
     */
    $(".errMsg-div #fromUpdate .alarmRadio").click(function (even) {
        console.log(even)
        $(this).addClass("active").siblings().removeClass("active")
    });
    $(".errMsg-div #fromUpdate  #rdWell").click(function () {
        let rdWell = '.errMsg-div #fromUpdate  #rdWell span b'
        let cancel = '.errMsg-div #fromUpdate  #cancel span'
        $(this[('span')]).css({"border": "1px solid #409EFF"})
        $(rdWell).css({"background-color": "#fff"})
        $(cancel).css({"border": "1px solid #dcdfe6"})
        $(cancel + ' b').css({"background-color": "rgba(0,0,0,0)"})
    });
    $(".errMsg-div #fromUpdate  #cancel").click(function () {
        let cancel = '.errMsg-div #fromUpdate  #cancel span b'
        let rdWell = '.errMsg-div #fromUpdate  #rdWell span'
        $(this[('span')]).css({"border": "1px solid #409EFF"})
        $(cancel).css({"background-color": "#fff"})
        $(rdWell).css({"border": "1px solid #dcdfe6"})
        $(rdWell + ' b').css({"background-color": "rgba(0,0,0,0)"})

    });


    /**
     * 警报信息提交!
     */
    $('#update').click(function () {
        $('#loading').css({display: 'block'});
        var data = $("#fromUpdate").serialize();
        var url = "../../Abnormal/updateAbnormalTable.do";
        $.ajax({
            "url": url,
            "type": "POST",
            "async": true,
            "cache": false,
            "data": data,
            "dataType": "json",
            beforeSend: function () {
                $('#loading').css({display: 'block'});
                layer.msg('正在连接邮箱服务器....');
            },
            "success": function (json) {
                $("#BJxx_chuli2").slideUp();
                $('#loading').css({display: 'none'});
                history.go(0)
            },
            error: function (){
                $("#BJxx_chuli2").slideUp();
                $('#loading').css({display: 'none'});
                history.go(0)
            }
        })
    })
})


// 总数, 已处理报警, 未处理报警
var Policezs = 0, PoliceOK = 0, PoliceNO = 0
newbaojing.forEach(item =>{
    item.status === 1 ? PoliceOK++ : PoliceNO++
    Policezs = PoliceOK + PoliceNO
})

let PoliceArr = $("#Policezs span")
for (let i = 0; i <PoliceArr.length; i++) {
    PoliceArr[i].innerHTML = setStr('0000', Policezs)[i]
    $("#PoliceOK span")[i].innerHTML = setStr('0000', PoliceOK)[i]
    $("#PoliceNO span")[i].innerHTML = setStr('0000', PoliceNO)[i]
}


var dom = document.getElementById("handleRate");
var myChart = echarts.init(dom);
var app = {};
option = null;
app.title = '环形图';
var centervalue1 = PoliceOK / (PoliceOK + PoliceNO) * 100;
option = {
    tooltip: {trigger: 'item', formatter: "{a} <br/>{b}: {c} "},
    color: ['#01B0F1', 'rgba(255,255,255,0.1)'],
    series: [{
        name: '设备概括',
        type: 'pie',
        radius: ['70%', '88%'],
        avoidLabelOverlap: false,
        label: {
            show: true, position: 'center', formatter: function (argument) {
                var html;
                html = '处理率\r\n\r\n' + centervalue1.toFixed(2) + '%';
                return html
            }, textStyle: {fontSize: 15, color: '#39CCCC'}
        },
        labelLine: {normal: {show: false}},
        data: [{value: PoliceOK, name: '已处理'}, {value: PoliceNO, name: '未处理'},]
    }, {type: 'pie', silent: true, radius: ['99%', '99.5%'], label: {show: false,}, data: [{value: 100},]}]
};
if (option && typeof option === "object") {
    myChart.setOption(option, true);
    window.addEventListener("resize", function () {
        myChart.resize()
    })
}
